package com.lly.bigdata.bgayx.security.service;

import com.lly.bigdata.bgayx.common.constants.Constants;
import com.lly.bigdata.bgayx.common.redis.RedisCache;
import com.lly.bigdata.bgayx.common.utils.IpUtils;
import com.lly.bigdata.bgayx.common.utils.MessageUtils;
import com.lly.bigdata.bgayx.common.utils.ServletUtils;
import com.lly.bigdata.bgayx.common.utils.StringUtils;
import com.lly.bigdata.bgayx.entity.SysUser;
import com.lly.bigdata.bgayx.exception.ServiceException;
import com.lly.bigdata.bgayx.exception.user.CaptchaException;
import com.lly.bigdata.bgayx.exception.user.CaptchaExpireException;
import com.lly.bigdata.bgayx.exception.user.UserPasswordNotMatchException;
import com.lly.bigdata.bgayx.manager.AsyncManager;
import com.lly.bigdata.bgayx.manager.factory.AsyncFactory;
import com.lly.bigdata.bgayx.service.ISysConfigService;
import com.lly.bigdata.bgayx.service.ISysLoginService;
import com.lly.bigdata.bgayx.service.ISysUserService;
import com.lly.bigdata.bgayx.vo.LoginUser;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 登录用户
 */
@Service
public class SysLoginService implements ISysLoginService {

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 登录操作
     *
     * @param username
     * @param password
     * @param code
     * @param uuid
     * @return
     */
    @Override
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, code, uuid);
        }
        Authentication authenticate = null;
        try {
            authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        recordLoginInfo(principal.getUserId());
        return tokenService.createToken(principal);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    public void recordLoginInfo(Long userId) {
        userService.updateUserProfile(userId, IpUtils.getIpAddr(ServletUtils.getRequest()), new Date());
    }
}
